const express = require('express');
const router = express.Router();
const path = require('path');
const fs = require('fs');
const tool = require('../../../tool.js');
const user = require('../../../model/User.js');

const docTypeMap = {
    HTML: 'html',
    CSS: 'css',
    Markdown: 'md',
    JavaScript: 'js',
    Plain: 'txt'
}

function setIO(io) {
    io.on('connection', (socket) => {
        socket.on('/application/Vititor/data/save/', (arg) => {
            const filePath = path.join(__dirname, `../../../user/user_${arg.user.name}/files`);
            const fileDirPath = path.join(filePath, 'fileDir.json');

            // 写入文档记录
            let fullDirData = {};
            tool.dirExists(filePath).then((value) => {
                if (tool.isFile(fileDirPath)) {
                    fs.readFile(fileDirPath, (err, data) => {
                        if (err) throw err;
                        fullDirData = JSON.parse(data);
                        fullDirData[`${arg.fileName}.${docTypeMap[arg.docType]}`] = { docType: arg.docType };
                        // 文件目录写入文件
                        fs.writeFile(path.join(filePath, `fileDir.json`), JSON.stringify(fullDirData), (err) => {
                            if (err) throw err;
                        });
                    });
                } else {
                    fullDirData[`${arg.fileName}.${docTypeMap[arg.docType]}`] = { docType: arg.docType };
                    // 文件目录写入文件
                    fs.writeFile(path.join(filePath, `fileDir.json`), JSON.stringify(fullDirData), (err) => {
                        if (err) throw err;
                    });
                }

                if (arg.fileName === 'README' && arg.docType === 'Markdown' && arg.text === '') {
                    fs.readFile(path.join(__dirname, '../../README.md'), (err, data) => {
                        if (err) throw err;
                        fs.writeFile(path.join(filePath, `README.md.txt`), data.toString(), (err) => {
                            if (err) throw err;
                        });
                    });
                } else {
                    // 写入文件
                    fs.writeFile(path.join(filePath, `${arg.fileName}.${docTypeMap[arg.docType]}.txt`), arg.text, (err) => {
                        if (err) throw err;
                    });
                }

                user.addFile(arg.user.name, {
                    "icon": `/application/Viditor/images/${docTypeMap[arg.docType]}.png`,
                    "name": `${arg.fileName}.${docTypeMap[arg.docType]}`,
                    "projectName": "Viditor",
                    "url": `/application/Viditor/index.html?userName=${arg.user.name}&fileName=${arg.fileName}&docType=${docTypeMap[arg.docType]}`,
                }, docTypeMap[arg.docType], (data) => {
                    data && socket.emit('/application/Vititor/data/save/', JSON.stringify(data));
                });

                console.log(`[${arg.user.name}]文件[${arg.fileName}.${docTypeMap[arg.docType]}]保存成功！`);
            }).catch((result) => {
                console.log(result);
                console.log(`[${arg.user.name}]文件[${arg.fileName}.${docTypeMap[arg.docType]}]保存失败！`);
                socket.emit('/application/Vititor/data/save/', { status: false, type: `File[${arg.fileName}]` });
            });
        });

        socket.on('/application/Vititor/data/get/', (arg) =>{
            const userPath = path.join(__dirname, `../../../user/user_${arg.userName}/files`);
            fs.readFile(path.join(userPath, `${arg.fileName}.${arg.docType}.txt`), (err, data) => {
                if (err) throw err;

                const content = data.toString();
                fs.readFile(path.join(userPath, `fileDir.json`), (err, data) => {
                    if (err) throw err;
                    const docType = JSON.parse(data)[`${arg.fileName}.${arg.docType}`].docType;
                    socket.emit('/application/Vititor/data/get/', JSON.stringify({
                        docType: docType,
                        content: content,
                        fileName: arg.fileName
                    }));
                    console.log(`[${arg.userName}]文件[${arg.fileName}.${arg.docType}]获取成功！`);
                });
            });
        });
    });
}

router.setIO = setIO;

module.exports = router;